<template>
  <PageContainer
    title="发车管理"
    description="管理车辆发车、查询订单装车情况"
    :actions="actions"
    :columns="columns"
    :data-source="dataSource"
    :loading="loading"
    :show-filters="true"
    :query-params="queryParams"
    :pagination-data="paginationData"
    :scroll="{ x: 1200, y: 'calc(100vh - 350px)' }"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 查询条件 -->
    <template #filter-items>
      <a-form-item label="车牌号/司机">
        <a-input
          v-model:value="queryParams.keyword"
          placeholder="输入车牌号或司机姓名"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="订单编号">
        <a-input
          v-model:value="queryParams.orderNumber"
          placeholder="输入订单编号"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="收货人">
        <a-input
          v-model:value="queryParams.receiver"
          placeholder="输入收货人姓名/电话"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="发车状态">
        <a-select
          v-model:value="queryParams.status"
          placeholder="选择发车状态"
          allow-clear
        >
          <a-select-option value="">全部状态</a-select-option>
          <a-select-option value="READY">待发车</a-select-option>
          <a-select-option value="DISPATCHED">已发车</a-select-option>
          <a-select-option value="ARRIVED">已到达</a-select-option>
          <a-select-option value="CANCELLED">已取消</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="发车日期">
        <a-range-picker
          v-model:value="queryParams.dispatchDateRange"
          :placeholder="['开始日期', '结束日期']"
          format="YYYY-MM-DD"
        />
      </a-form-item>

      <a-form-item label="目的地">
        <a-input
          v-model:value="queryParams.destination"
          placeholder="输入目的地"
          allow-clear
        />
      </a-form-item>
    </template>

    <!-- 表格内容 -->
    <template #bodyCell="{ column, record }">
      <!-- 车辆信息列 -->
      <template v-if="column.key === 'vehicleInfo'">
        <div class="vehicle-info">
          <div class="vehicle-main">
            <span class="vehicle-plate">{{ record.vehiclePlate }}</span>
          </div>
        </div>
      </template>

      <!-- 司机信息列 -->
      <template v-if="column.key === 'driverInfo'">
        <div class="driver-info">
          <div class="driver-name">{{ record.driverName }}</div>
          <div class="driver-phone">{{ record.driverPhone }}</div>
        </div>
      </template>

      <!-- 订单数量列 -->
      <template v-else-if="column.key === 'orderCount'">
        <span style="color: #6366f1; font-weight: 500">
          {{ record.orderCount || 0 }}
        </span>
      </template>

      <!-- 发车状态列 -->
      <template v-else-if="column.key === 'dispatchStatus'">
        <a-tag :color="getStatusColor(record.dispatchStatus)">
          {{ getStatusText(record.dispatchStatus) }}
        </a-tag>
      </template>

      <!-- 操作列 -->
      <template v-else-if="column.key === 'actions'">
        <a-space size="small">
          <a-button
            v-if="record.dispatchStatus === 'READY'"
            type="link"
            size="small"
            @click="handleConfirmDispatch(record)"
          >
            确认发车
          </a-button>
          <a-button
            type="link"
            size="small"
            @click="handleViewVehicleOrders(record)"
          >
            查看订单
          </a-button>
          <!-- 删除按钮（待发车和已取消状态） -->
          <a-popconfirm
            v-if="
              record.dispatchStatus === 'READY' ||
              record.dispatchStatus === 'CANCELLED'
            "
            title="确定删除该发车记录吗？删除后无法恢复！"
            ok-text="确定删除"
            cancel-text="取消"
            @confirm="handleDeleteDispatch(record)"
          >
            <a-button type="link" size="small" danger> 删除 </a-button>
          </a-popconfirm>

          <!-- 取消发车按钮（仅已发车状态） -->
          <a-popconfirm
            v-if="record.dispatchStatus === 'DISPATCHED'"
            title="确定取消该发车吗？"
            ok-text="确定取消"
            cancel-text="取消"
            @confirm="handleCancelDispatch(record)"
          >
            <a-button type="link" size="small" danger> 取消发车 </a-button>
          </a-popconfirm>

          <!-- 重新发车按钮（仅已取消状态） -->
          <a-popconfirm
            v-if="record.dispatchStatus === 'CANCELLED'"
            title="确定重新发车吗？"
            ok-text="确定发车"
            cancel-text="取消"
            @confirm="handleRestartDispatch(record)"
          >
            <a-button type="link" size="small" style="color: #52c41a">
              重新发车
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </PageContainer>

  <!-- 新建发车弹窗 -->
  <a-modal
    v-model:open="createModalVisible"
    title="新建发车"
    width="600px"
    @ok="handleCreateDispatch"
    @cancel="handleCreateCancel"
  >
    <a-form
      :model="createForm"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="车辆类型" required>
        <a-radio-group v-model:value="createForm.vehicleType">
          <a-radio value="company">公司车辆</a-radio>
          <a-radio value="temp">临时车辆</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 公司车辆选择 -->
      <a-form-item
        v-if="createForm.vehicleType === 'company'"
        label="选择车辆"
        required
      >
        <a-select
          v-model:value="createForm.vehicleId"
          placeholder="请选择车辆"
          @change="handleVehicleChange"
        >
          <a-select-option
            v-for="vehicle in vehicleOptions"
            :key="vehicle.id"
            :value="vehicle.id"
          >
            {{ vehicle.plateNumber }} - {{ vehicle.ownerName || "未填写" }}
            <span
              v-if="vehicle.hasDispatch"
              style="color: #ff4d4f; margin-left: 8px"
            >
              (已有发车记录)
            </span>
          </a-select-option>
        </a-select>
      </a-form-item>

      <!-- 临时车辆信息 -->
      <template v-if="createForm.vehicleType === 'temp'">
        <a-form-item label="车牌号" required>
          <a-input
            v-model:value="createForm.tempVehiclePlate"
            placeholder="请输入车牌号"
            maxlength="10"
          />
        </a-form-item>

        <a-form-item label="司机姓名" required>
          <a-input
            v-model:value="createForm.tempDriverName"
            placeholder="请输入司机姓名"
            maxlength="20"
          />
        </a-form-item>

        <a-form-item label="司机电话">
          <a-input
            v-model:value="createForm.tempDriverPhone"
            placeholder="请输入司机电话"
            maxlength="11"
          />
        </a-form-item>
      </template>

      <a-form-item label="目的站点" required>
        <a-select
          v-model:value="createForm.destination"
          placeholder="请选择目的站点"
        >
          <a-select-option
            v-for="site in siteOptions"
            :key="site.id"
            :value="site.siteName"
          >
            {{ site.siteName }} ({{ site.siteCode }})
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="备注">
        <a-textarea
          v-model:value="createForm.remark"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { SendOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import PageContainer from "@/components/business/PageContainer.vue";

const router = useRouter();

// 查询参数
const queryParams = reactive({
  keyword: "",
  orderNumber: "",
  receiver: "",
  status: "",
  dispatchDateRange: null,
  destination: "",
});

// 页面数据
const dataSource = ref([]);
const loading = ref(false);

// 分页数据
const paginationData = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});

// 新建发车弹窗状态
const createModalVisible = ref(false);
const createForm = reactive({
  vehicleType: "company", // company | temp
  vehicleId: undefined,
  // 临时车辆字段
  tempVehiclePlate: "",
  tempDriverName: "",
  tempDriverPhone: "",
  destination: undefined as string | undefined,
  remark: "",
});
const vehicleOptions = ref<any[]>([]);
const siteOptions = ref<any[]>([]);

// 操作按钮
const actions = [
  {
    key: "dispatch",
    label: "新建发车",
    type: "primary" as const,
    icon: SendOutlined,
    onClick: () => {
      createModalVisible.value = true;
    },
  },
];

// 表格列配置
const columns = [
  {
    title: "车辆信息",
    key: "vehicleInfo",
    width: 150,
  },
  {
    title: "司机信息",
    key: "driverInfo",
    width: 150,
  },
  {
    title: "发车时间",
    dataIndex: "actualDepartureTime",
    key: "actualDepartureTime",
    width: 180,
  },
  {
    title: "到达时间",
    dataIndex: "actualArrivalTime",
    key: "actualArrivalTime",
    width: 180,
  },
  {
    title: "始发站",
    dataIndex: "departureSiteName",
    key: "departureSiteName",
    width: 120,
  },
  {
    title: "目的地",
    dataIndex: "arrivalSiteName",
    key: "arrivalSiteName",
    width: 120,
  },
  {
    title: "订单数量",
    key: "orderCount",
    dataIndex: "orderCount",
    width: 100,
    align: "center" as const,
  },
  {
    title: "发车状态",
    key: "dispatchStatus",
    width: 100,
  },
  {
    title: "操作",
    key: "actions",
    width: 250,
    align: "center",
    fixed: "right" as const,
  },
];

// 获取状态颜色 - 符合项目主题
const getStatusColor = (status: string) => {
  const statusColors: Record<string, string> = {
    READY: "warning", // 橙色 - 待发车
    DISPATCHED: "processing", // 蓝色 - 已发车进行中
    ARRIVED: "success", // 绿色 - 已到达
    CANCELLED: "error", // 红色 - 已取消
  };
  return statusColors[status] || "default";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusTexts: Record<string, string> = {
    READY: "待发车",
    DISPATCHED: "已发车",
    ARRIVED: "已到达",
    CANCELLED: "已取消",
  };
  return statusTexts[status] || "未知";
};

// 查看车辆订单详情
const handleViewVehicleOrders = async (record: any) => {
  try {
    // 跳转到车辆订单页面，传递完整的车辆和司机信息
    router.push({
      path: `/tenant/dispatch/vehicle/${record.vehicleId}`,
      query: {
        vehiclePlate: record.vehiclePlate,
        driverName: record.driverName || "",
        driverPhone: record.driverPhone || "",
        driverId: record.driverId || "",
      },
    });
  } catch (error) {
    message.error("跳转车辆订单页面失败");
    console.error("Navigate to vehicle orders error:", error);
  }
};

// 获取车辆列表
const fetchVehicleOptions = async () => {
  try {
    const { getVehicleList } = await import("@/api/tenant/vehicle");
    const { getDispatchList } = await import("@/api/dispatch");

    // 获取车辆列表和发车记录
    const [vehicleResponse, dispatchResponse] = await Promise.all([
      getVehicleList({ current: 1, size: 1000 }),
      getDispatchList({ current: 1, size: 1000, dispatchStatus: "READY" }),
    ]);

    if (vehicleResponse.data) {
      const vehicles = vehicleResponse.data.records || [];
      const dispatches = dispatchResponse.data?.records || [];

      // 标记已有发车记录的车辆
      vehicleOptions.value = vehicles.map((vehicle: any) => ({
        ...vehicle,
        hasDispatch: dispatches.some(
          (dispatch: any) => dispatch.vehicleId === vehicle.id
        ),
      }));
    }
  } catch (error) {
    console.error("Fetch vehicle options error:", error);
  }
};

// 车辆选择变化处理
const handleVehicleChange = (vehicleId: number) => {
  const selectedVehicle = vehicleOptions.value.find((v) => v.id === vehicleId);
  if (selectedVehicle?.hasDispatch) {
    message.warning("该车辆已有待发车记录，请确认是否继续创建");
  }
};

// 获取站点列表（排除当前站点）
const fetchSiteOptions = async () => {
  try {
    const { getSiteList, getCurrentSite } = await import("@/api/tenant/site");

    // 获取所有站点和当前站点
    const [siteListResponse, currentSiteResponse] = await Promise.all([
      getSiteList(),
      getCurrentSite(),
    ]);

    if (siteListResponse.data && currentSiteResponse.data) {
      const currentSiteId = currentSiteResponse.data.id;
      // 排除当前站点
      siteOptions.value = siteListResponse.data.filter(
        (site: any) => site.id !== currentSiteId
      );
    }
  } catch (error) {
    console.error("Fetch site options error:", error);
  }
};

// 新建发车处理
const handleCreateDispatch = async () => {
  // 验证必填项
  if (createForm.vehicleType === "company") {
    if (!createForm.vehicleId || !createForm.destination) {
      message.error("请填写必填项");
      return;
    }
  } else {
    if (
      !createForm.tempVehiclePlate ||
      !createForm.tempDriverName ||
      !createForm.destination
    ) {
      message.error("请填写必填项");
      return;
    }
  }

  try {
    if (createForm.vehicleType === "company") {
      // 公司车辆
      const { createDispatch } = await import("@/api/dispatch");
      await createDispatch(
        createForm.vehicleId,
        createForm.destination,
        createForm.remark
      );
    } else {
      // 临时车辆
      const { createTempDispatch } = await import("@/api/dispatch");
      await createTempDispatch(
        createForm.tempVehiclePlate,
        "TRUCK", // 默认车辆类型
        createForm.destination,
        createForm.tempDriverName,
        createForm.tempDriverPhone,
        createForm.remark
      );
    }

    message.success("发车记录创建成功");
    createModalVisible.value = false;
    handleCreateCancel();
    fetchData();
  } catch (error) {
    message.error("创建发车记录失败");
    console.error("Create dispatch error:", error);
  }
};

// 取消新建发车
const handleCreateCancel = () => {
  createForm.vehicleType = "company";
  createForm.vehicleId = undefined;
  createForm.tempVehiclePlate = "";
  createForm.tempDriverName = "";
  createForm.tempDriverPhone = "";
  createForm.destination = undefined;
  createForm.remark = "";
};

// 删除发车记录（物理删除）
const handleDeleteDispatch = async (record: any) => {
  try {
    const { deleteDispatch } = await import("@/api/dispatch");

    await deleteDispatch(record.id);
    message.success("发车记录删除成功");
    fetchData();
  } catch (error) {
    message.error(error.message);
    console.error("Delete dispatch error:", error);
  }
};

// 取消发车（状态变更）
const handleCancelDispatch = async (record: any) => {
  try {
    const { cancelDispatch } = await import("@/api/dispatch");

    await cancelDispatch(record.id, "用户取消发车");
    message.success("发车已取消");
    fetchData();
  } catch (error) {
    message.error("取消发车失败");
    console.error("Cancel dispatch error:", error);
  }
};

// 重新发车（从已取消状态恢复到已发车状态）
const handleRestartDispatch = async (record: any) => {
  try {
    const { confirmDispatch } = await import("@/api/dispatch");

    await confirmDispatch({
      dispatchId: record.id,
      actualDepartureTime: new Date().toISOString().slice(0, 19),
      remark: "重新发车",
    });

    message.success("重新发车成功");
    fetchData();
  } catch (error) {
    message.error("重新发车失败");
    console.error("Restart dispatch error:", error);
  }
};

// 确认发车
const handleConfirmDispatch = async (record: any) => {
  try {
    const { confirmDispatch } = await import("@/api/dispatch");

    // 获取本地时间，格式: YYYY-MM-DD HH:mm:ss
    const now = new Date();
    const localTime =
      now.getFullYear() +
      "-" +
      String(now.getMonth() + 1).padStart(2, "0") +
      "-" +
      String(now.getDate()).padStart(2, "0") +
      "T" +
      String(now.getHours()).padStart(2, "0") +
      ":" +
      String(now.getMinutes()).padStart(2, "0") +
      ":" +
      String(now.getSeconds()).padStart(2, "0");

    await confirmDispatch({
      dispatchId: record.id,
      actualDepartureTime: localTime,
      remark: "确认发车",
    });

    message.success("发车确认成功");
    fetchData();
  } catch (error) {
    message.error("确认发车失败");
    console.error("Confirm dispatch error:", error);
  }
};

// 搜索
const handleSearch = () => {
  paginationData.current = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  Object.keys(queryParams).forEach((key) => {
    queryParams[key as keyof typeof queryParams] =
      key === "dispatchDateRange" ? null : "";
  });
  paginationData.current = 1;
  fetchData();
};

// 分页变化
const handlePaginationChange = (page: number, pageSize: number) => {
  paginationData.current = page;
  paginationData.pageSize = pageSize;
  fetchData();
};

// 获取发车列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const { getDispatchList } = await import("@/api/dispatch");

    const response = await getDispatchList({
      ...queryParams,
      current: paginationData.current,
      size: paginationData.pageSize,
      dispatchStartDate: queryParams.dispatchDateRange?.[0] || undefined,
      dispatchEndDate: queryParams.dispatchDateRange?.[1] || undefined,
    });

    if (response.data) {
      dataSource.value = response.data.records || [];
      paginationData.total = response.data.total || 0;
    }
  } catch (error) {
    message.error("获取发车列表失败");
    console.error("Fetch dispatch data error:", error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
  fetchVehicleOptions();
  fetchSiteOptions();
});
</script>

<style scoped>
.vehicle-info {
  .vehicle-main {
    display: flex;
    align-items: center;
    gap: 8px;

    .vehicle-icon {
      color: var(--primary-color);
      font-size: 16px;
    }

    .vehicle-plate {
      font-weight: 500;
      color: var(--text-primary);
      letter-spacing: 0.5px;
    }
  }
}

.driver-info {
  .driver-name {
    font-weight: 500;
    color: var(--text-primary);
  }

  .driver-phone {
    font-size: 12px;
    color: var(--text-secondary);
  }
}

.order-info {
  text-align: center;

  .ant-btn-link {
    padding: 0;
    height: auto;
    color: var(--primary-color);

    &:hover {
      color: var(--primary-hover);
    }
  }
}

/* 操作按钮样式优化 */
:deep(.ant-space-item) {
  .ant-btn-sm {
    display: flex;
    align-items: center;
    gap: 4px;

    .anticon {
      font-size: 12px;
    }
  }

  .ant-btn-primary {
    background-color: var(--primary-color);
    border-color: var(--primary-color);

    &:hover {
      background-color: var(--primary-hover);
      border-color: var(--primary-hover);
    }
  }
}
</style>
